<?php
namespace Wap\Controller;
use Think\Controller;

class ZJDailyCardController extends Controller
{
    private $zjdailyCardCustomer = null;

    public function __construct()
    {
        parent::__construct();
        $this->zjdailyCardCustomer = session("zjdailyCardCustomer.login");
        $_GET && $this->SafeFilter($_GET);
        $_POST && $this->SafeFilter($_POST);
        $_COOKIE && $this->SafeFilter($_COOKIE);

    }

    public function SafeFilter(&$arr)
    {

        $ra = Array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '/script/', '/javascript/', '/vbscript/', '/expression/', '/applet/', '/meta/', '/xml/', '/blink/', '/link/', '/style/', '/embed/', '/object/', '/frame/', '/layer/', '/title/', '/bgsound/', '/base/', '/onload/', '/onunload/', '/onchange/', '/onsubmit/', '/onreset/', '/onselect/', '/onblur/', '/onfocus/', '/onabort/', '/onkeydown/', '/onkeypress/', '/onkeyup/', '/onclick/', '/ondblclick/', '/onmousedown/', '/onmousemove/', '/onmouseout/', '/onmouseover/', '/onmouseup/', '/onunload/');

        if (is_array($arr)) {
            foreach ($arr as $key => $value) {
                if (!is_array($value)) {
                    if (!get_magic_quotes_gpc())             //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
                    {
                        $value = addslashes($value);           //给单引号（'）、双引号（"）、反斜线（\）与 NUL（NULL 字符）加上反斜线转义
                    }
                    $value = preg_replace($ra, '', $value);     //删除非打印字符，粗暴式过滤xss可疑字符串
                    $arr[$key] = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体
                } else {
                    SafeFilter($arr[$key]);
                }
            }
        }
    }

    public function index()
    {
        return $this->display();
        $bag = I("get.bag", array(), "");
        if (is_array($bag) && !count($bag)) {
            return $this->display();
        }

        $data_card['customer_id'] = $this->zjdailyCardCustomer;
        if (!$data_card['customer_id']) {
            $this->error("用户未登录", U('Wap/ZJDailyCard/index'));
        }

        $data_card['addr_id'] = I("get.addr_id", -1, "");
        $data_card['username'] = I("get.username", "", "");
        $data_card['telephone'] = I("get.telephone", "", "");
        $data_card['cardnumber'] = I("get.cardnumber", "", "");
        $data_card['province'] = I("get.province", "", "");
        $data_card['city'] = I("get.city", "", "");
        $data_card['county'] = I("get.county", "", "");
        $data_card['address'] = I("get.address", "", "");
        $data_card['metier'] = I("get.metier", "", "");

        foreach ($data_card as $key => $value) {
            $data_card[$key] = $value;
        }

        $exist = array();
        if ($data_card['addr_id'] != -1) {
            $exist = M("customer_addr")->field("province, city, county, address")
                ->where(array('id' => $data_card['addr_id'], 'customer_id' => $data_card['customer_id'], 'scope' => 'zjdailycard'))
                //->order( "signtime desc" )
                ->find();
            if (!count($exist)) {
                $exist = array("province" => "", "city" => "", "county" => "", "address" => "");
            }
            $data_card = array_merge($data_card, $exist);
        }
        $bag = array();
        $bag['data_card'] = $data_card;

        $this->assign("bag", $bag);
        $this->display();
    }

    public function edit()
    {
        $condition['esm_zjrb_card.id'] = I("get.cardId", -1, "");
        $condition['scope'] = 'zjdailycard';

        $card = M("zjrb_card")->field(array(
            "esm_zjrb_card.id" => "id",
            "esm_zjrb_card.cardnumber" => "cardnumber",
            "esm_zjrb_card.status" => 'status',
            "esm_addr.username" => "username",
            "esm_addr.telephone" => "telephone",
            "esm_addr.province" => "province",
            "esm_addr.city" => "city",
            "esm_addr.county" => "county",
            "esm_addr.address" => "address",
            'esm_addr.metier' => 'metier'))
            ->join("LEFT JOIN esm_customer_addr as esm_addr ON esm_zjrb_card.addr_id = esm_addr.id")
            ->where($condition)
            ->find();
        if (!isset($card['status'])) {
            return $this->error("卡片未找到");
        } else if ($card['status'] > 1) {
            return $this->error("卡片已经导出，无法修改!");
        }
        $region = M("region")
            ->field(array(
                "esm_region.id" => 'id',
                'esm_region.regionname' => 'regionname'
            ))
            ->where(['id' => ['IN', [
                $card['province'],
                $card['city'],
                $card['county']]
            ]])->select();
        $province = "";
        $city = "";
        $county = "";
        foreach ($region as $value) {
            if ($value['id'] == $card['province']) {
                $province = $value['regionname'];
            }
            if ($value['id'] == $card['city']) {
                $city = $value['regionname'];
            }
            if ($value['id'] == $card['county']) {
                $county = $value['regionname'];
            }
        }
        $this->assign("province", $province);
        $this->assign("city", $city);
        $this->assign("county", $county);
        $this->assign("card", $card);
        $this->display();
    }

    public function home()
    {
        $customer_id = $this->zjdailyCardCustomer;
        if (!$customer_id) {
            $this->error("用户未登录", U('Wap/ZJDailyCard/index'));
        }
        $condition = array(
            'esm_zjrb_card.customer_id' => $customer_id,
            'status' => array('gt', -2)
        );
        $cards = M("zjrb_card")
            ->field(array(
                "esm_zjrb_card.id" => "id",
                "esm_zjrb_card.cardnumber" => "cardnumber",
                "esm_zjrb_card.status" => "status",
                "esm_addr.username" => 'username',
                'esm_addr.telephone' => 'telephone',
                'esm_addr.address' => 'address',
                'esm_province.regionname' => 'province',
                'esm_city.regionname' => 'city',
                'esm_county.regionname' => 'county'))
            ->join("LEFT JOIN esm_customer_addr as esm_addr ON esm_zjrb_card.addr_id = esm_addr.id")
            ->join("LEFT JOIN esm_region as esm_province ON esm_province.id = esm_addr.province")
            ->join("LEFT JOIN esm_region as esm_city ON esm_city.id = esm_addr.city")
            ->join("LEFT JOIN esm_region as esm_county ON esm_county.id = esm_addr.county")
            ->where($condition)
            ->order("esm_zjrb_card.signtime desc")
            ->select();
        $this->assign("cards", $cards);
        $this->display();
    }

    public function active()
    {
        /*$customer_id = $this->zjdailyCardCustomer;
        if (!$customer_id) {
            $exit = array('err' => 400, 'msg' => '用户不在线');
            $this->ajaxReturn($exit);
        }*/
        $_POST['status'] = 1;
        $updated = $this->update();
        $this->ajaxReturn($updated);
    }

    public function save()
    {
        $customer_id = $this->zjdailyCardCustomer;
        if (!$customer_id) {
            $exit = array('err' => 400, 'msg' => '用户不在线');
            $this->ajaxReturn($exit);
        }
        unset($_POST['status']);
        $updated = $this->update();
        $this->ajaxReturn($updated);
    }

    public function update()
    {
        $data['username'] = I("post.username", "", "");
        $data['telephone'] = I("post.telephone", "", "");
        $data['province'] = I("post.province", "", "");
        $data['city'] = I("post.city", "", "");
        $data['county'] = I("post.county", "", "");
        $data['address'] = I("post.address", "", "");
        $data['metier'] = I("post.metier", "", "");
        $data['cardId'] = I("post.cardId", "", "");
        $data['scope'] = 'zjdailycard';
        if (isset($_POST['metier'])) {
            $data['metier'] = I("post.metier", "", "");
        }

        $data['status'] = I("post.status", 1, "");
        $data['signtime'] = date("Y-m-d H:i:s");

        $result = array('err' => 404, 'msg' => '激活错误');
        if (empty($data['city']) or empty($data['county'])
            or empty($data['province']) or empty($data['address'])
        ) {
            $result['msg'] = '地址信息错误';
            return $result;
        }
        if (empty($data['username']) || empty($data['telephone'])) {
            $result['msg'] = '用户信息错误';
            return $result;
        }

        if (empty($data['cardId'])) {
            $result['msg'] = '请返回上一步，检查卡号！';
            return $result;
        }
        $card_info = explode("|", $data['cardId']);
        if (!is_array($card_info) && sizeof($card_info) != 2) {
            $result['msg'] = '请返回上一步，检查卡号';
            return $result;
        }
        $zjrb_card = M("zjrb_card")->where([
            'id' => $card_info[0],
            'password' => $card_info[1]
        ])->find();
        if (!$zjrb_card) {
            $result['msg'] = "卡号信息错误、不存在";
            return $result;
        } else if (isset($data['status']) && intval($zjrb_card['status']) > 0) {
            $result['err'] = 409;
            $result['msg'] = "该报卡已被使用过了";
            return $result;
        } else if (!isset($data['status']) && intval($zjrb_card['status']) > 1) {
            $result['err'] = 409;
            $result['msg'] = '报卡已经导出、无法修改';
            return $result;
        } else if (strtotime($zjrb_card['endtime']) < strtotime($zjrb_card['begintime'])) {
            $result['err'] = 409;
            $result['msg'] = '报卡信息不正确';
            return $result;
        } else if (time() > strtotime($zjrb_card['endtime'])) {
            $result['err'] = 409;
            $result['msg'] = '报卡已失效';
            return $result;
        } else if (time() < strtotime($zjrb_card['begintime'])) {
            $result['err'] = 409;
            $result['msg'] = '该报卡订阅未开始';
//            return $result;
        }
        $type = I("post.type", "", "");
        if($type === "check"){
            $result['err'] = 200;
            $result['msg'] = $zjrb_card['id'];
            return $result;
        }
        $customerAddr = D("CustomerAddr");
        $customerAddr->startTrans();
        $data['customer_id'] = "0";
        $result_addr = $customerAddr->add($data);
        if ($result_addr <= 0) {
            $result['msg'] = "数据保存出现错误";
            return;
        }
        $zjrb_card['status'] = $data['status'];
        $zjrb_card['addr_id'] = $result_addr;
        $zjrb_card['signtime'] = date("Y-m-d H:i:s");
        $updated = M("zjrb_card")->where('id=' . $zjrb_card['id'])->save($zjrb_card);
        if ($updated === false) {
            $customerAddr->rollback();
            $result['err'] = 417;
            $result['msg'] = "数据保存出现错误";
        } else {
            $customerAddr->commit();//TODO: could be better
            $result['err'] = 200;
            $result['msg'] = $zjrb_card['id'];
        }

        return $result;
    }


    //--2016-10-20新增--
    public function verifyCode()
    {
        $im = imagecreate($x = 90, $y = 35);
        imagecolorallocate($im, rand(50, 200), rand(0, 155), rand(0, 155)); //第一次对 imagecolorallocate() 的调用会给基于调色板的图像填充背景色
        $fontColor = imagecolorallocate($im, 255, 255, 255); //字体颜色
        $fontstyle = '/Public/fonts/verdanaz.ttf';
        $authcode = '';

        for ($i = 0; $i < 4; $i++) {
//            $randAsciiNumArray = array(rand(48, 57), rand(65, 90));
            $randAsciiNum = rand(48, 57);
            $randStr = chr($randAsciiNum);
            $authcode .= $randStr;
        }
        imagefttext($im, 19, 0, 5, 25, $fontColor, $fontstyle, $authcode);
        //--干扰线--
        for ($i = 0; $i < 8; $i++) {
            $lineColor = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
            imageline($im, rand(0, $x), 0, rand(0, $x), $y, $lineColor);
        }
        //--干扰点--
        for ($i = 0; $i < 250; $i++) {
            imagesetpixel($im, rand(0, $x), rand(0, $y), $fontColor);
        }
        ob_clean();
        header('Content-type: image/png');
        imagepng($im);
        imagedestroy($im);
        session('verifyCode', $authcode);
    }

    public function checkCard()
    {
        $data_card['cardnumber'] = I("post.cardno", "", "");
        $data_card['password'] = strtoupper(I("post.password", "", ""));
        $data_card['verify_code'] = I("post.verify_code", "", "");
        if (strtoupper($data_card['verify_code']) != session('verifyCode')) {
            echo json_encode(['code' => -1, 'msg' => '验证码错误！']);
            return;
        }
        if (empty($data_card['cardnumber']) || empty($data_card['password'])) {
            echo json_encode(['code' => -1, 'msg' => '用户名密码不能为空！']);
            return;
        }
        $zjrb_card_obj = M('zjrb_card')->where([
            'cardnumber' => $data_card['cardnumber'],
            'password' => $data_card['password']
        ])->find();
        if (empty($zjrb_card_obj)) {
            echo json_encode(['code' => -1, 'msg' => '用户名/密码错误！']);
            return;
        }
        if ($zjrb_card_obj['status'] > -1) {
            echo json_encode(['code' => -1, 'msg' => '已激活使用，不可重新激活！']);
            return;
        }
        session('verify_code', "");
        echo json_encode(['code' => 1, 'msg' => $zjrb_card_obj['id'] . "|" . $zjrb_card_obj['password']]);
    }

    public function next()
    {
        $data_card['cardId'] = I("get.cardId", "", "");
        $this->assign("cardId", $data_card['cardId']);
        $this->display();
    }

    public function check()
    {
        $data["id"] = I("get.cardId", "", "");
        $card_id = explode("|", $data["id"]);
        $data['cardnumber'] = M("zjrb_card")->where("id=" . $card_id[0])->getField("cardnumber");
        $data['username'] = I("get.username", "", "");
        $data['telephone'] = I("get.telephone", "", "");
        $data['province'] = I("get.province", "", "");
        $data['provincename'] = M("region")->where("id=" . $data['province'])->getField("regionname");
        $data['city'] = I("get.city", "", "");
        $data['cityname'] = M("region")->where("id=" . $data['city'])->getField("regionname");
        $data['county'] = I("get.county", "", "");
        $data['countyname'] = M("region")->where("id=" . $data['county'])->getField("regionname");
        $data['address'] = I("get.address", "", "");
        $data['metier'] = I("get.metier", "", "");
        $data['cardId'] = I("get.cardId", "", "");
        $this->assign("card", $data);
        $this->display();
    }

    public function cash()
    {
        return $this->display();
    }

    public function payment()
    {
        return $this->display();
    }

    public function address()
    {
        return $this->display();
    }

    public function order()
    {
        return $this->display();
    }
}

?>
